#include "Log.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
using namespace LogModule;
// 我们的客户端不需要像服务端那样显式的绑定我们的ip和port，一般都是os帮助我们做了
// 我们这里只是需要创建套接字和发送和接收消息即可
int main(int argc, char* argv[]) {
    if(argc != 3) {
        cout << "The usage is " << argv[0] << "+server_ip+server_port" << endl;
        return 1;
    }
    string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0) {
        LOG(LogLevel::FATAL) << "socket error";
        return 2;
    }
    // 填写相关的服务端的信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    while (1) {
        std::string in;
        std::cout << "Please Enter# ";
        std::getline(std::cin, in);
        int n = sendto(sockfd, in.c_str(), in.size(), 0, (struct sockaddr*)&server, sizeof(server));
        (void)n;
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0) {
            buffer[m] = '\0';
            std::cout << buffer << std::endl;
        }
    }
    return 0;
}